package com.github.zhp;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.github.zhp.startup.ConfigJson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 自动生成入口类
 *
 * @author zhoup
 */
public class GenerateStarter {
    private ConfigJson jsonConfig = null;

    public GenerateStarter() {
    }

    public void setJsonConfig(ConfigJson jsonConfig) {
        this.jsonConfig = jsonConfig;
    }

    public GenerateStarter(String configPath) {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        try (Stream<String> lines = Files.lines(Paths.get(configPath))) {
            String jsonStr = lines
                    .map(String::trim)
                    .filter(s -> !s.startsWith("//"))
                    .collect(Collectors.joining());
            ConfigJson configJson = gson.fromJson(jsonStr, ConfigJson.class);
            System.out.println("配置文件：" + jsonStr);
            this.jsonConfig = configJson;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() {
        ConfigurationDelegator config = new ConfigurationDelegator();
        if (jsonConfig != null) {
            ConfigContext.setSelfConfigJson(jsonConfig);
            config.setConfig(jsonConfig);
            if (jsonConfig.isUseSql()) {
                try {
                    config.init();
                } catch (SQLException | IOException throwables) {
                    throw new RuntimeException(throwables);
                }
            }
        }

//        StrategyConfig strategyConfig = config.getStrategyConfig();
//        strategyConfig.controllerBuilder().enableHyphenStyle()
        // 初始化配置数据源
        new AutoGenerator(config.getDataSourceConfig())
                // 全局配置
                .global(config.getGlobalConfig())
                // 模板配置
                .template(config.getTemplateConfig())
                // 包配置
                .packageInfo(config.getPackageConfig())
                // 策略配置
                .strategy(config.getStrategyConfig())
                // 注入配置
                .injection(config.getInjectionConfig())
                //模版根路径
                .setBaseTemplatePath(jsonConfig.getBaseTemplatePath())
                // 执行
                .execute(config.templateEngine());
    }
}
